﻿using Common;
using Common.Utility.AJ.Extension;
using DocumentFormat.OpenXml.Bibliography;
using Stylet;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace AWSV2.Models
{
    public class WeightInputFormModel : PropertyChangedBase
    {

        private int _weightValueDisplayFormat;
        public int WeightValueDisplayFormat
        {
            get
            {
                return _weightValueDisplayFormat;
            }
            set
            {
                SetAndNotify(ref _weightValueDisplayFormat, value);
            }
        }

        private decimal _grossWeight;
        public decimal GrossWeight
        {
            get => _grossWeight;
            set
            {
                if (SetAndNotify(ref _grossWeight, value))
                {
                    ComputeWeight();
                }
            }
        }

        private string _tareWeight;
        public string TareWeight
        {
            get => _tareWeight;
            set
            {
                if (SetAndNotify(ref _tareWeight, value))
                {
                    if (decimal.TryParse(value, out _tareWeightVal))
                    {
                        ComputeWeight();
                    }
                }
            }
        }

        private decimal _tareWeightVal;
        public decimal TareWeightValue
        {
            get => _tareWeightVal;
            private set => _tareWeightVal = value;
        }

        private decimal _netWeight;
        public decimal NetWeight
        {
            get => _netWeight;
            set
            {
                if (SetAndNotify(ref _netWeight, value))
                {
                    //ComputeWeight();
                }
            }
        }

        private string _deductWeight;
        /// <summary>
        /// 扣重
        /// </summary>
        public string DeductWeight
        {
            get => _deductWeight;
            set
            {
                if (SetAndNotify(ref _deductWeight, value))
                {
                    if (decimal.TryParse(value, out _deductWeightValue))
                    {
                        ComputeWeight();
                    }
                }
            }
        }

        private decimal _deductWeightValue;
        public decimal DeductWeightValue
        {
            get => _deductWeightValue;
            private set => _deductWeightValue = value;
        }

        private string _weightDiscount;
        /// <summary>
        /// 扣率
        /// </summary>
        [Display(Name = "扣率")]
        [Range(0, 100, ErrorMessage = "{0}须在{1} ~ {2} 之间")]
        public string WeightDiscount
        {
            get => _weightDiscount;
            set
            {
                if (SetAndNotify(ref _weightDiscount, value))
                {
                    if (decimal.TryParse(value, out _weightDiscountValue))
                    {
                        ComputeWeight();
                    }
                }
            }
        }

        private decimal _weightDiscountValue;
        public decimal WeightDiscountValue
        {
            get => _weightDiscountValue;
            private set => _weightDiscountValue = value;
        }

        private decimal _realWeight;
        /// <summary>
        /// 实重
        /// </summary>
        public decimal RealWeight { get => _realWeight; set => SetAndNotify(ref _realWeight, value); }


        private Dictionary<string, bool> _discountOptions;
        public Dictionary<string, bool> DiscountOptions
        {
            get => _discountOptions;
            set => SetAndNotify(ref _discountOptions, value);
        }

        private bool _isDiscount;
        /// <summary>
        /// 是否是扣率
        /// </summary>
        public bool IsDiscount
        {
            get { return _isDiscount; }
            set
            {
                if (SetAndNotify(ref _isDiscount, value))
                {
                    ComputeWeight();
                }
            }
        }

        private List<string> _weighingTypeOptions;
        public List<string> WeighingTypeOptions
        {
            get => _weighingTypeOptions;
            set => SetAndNotify(ref _weighingTypeOptions, value);
        }

        private string _weighingType;
        public string WeighingType
        {
            get => _weighingType;
            set => SetAndNotify(ref _weighingType, value);
        }

        private void ComputeWeight()
        {
            if (_isDiscount)
            {
                //if (!ValidateModel())
                //{
                //    return;
                //}
            }

            NetWeight = Math.Round(GrossWeight - TareWeightValue, WeightValueDisplayFormat, MidpointRounding.AwayFromZero);

            RealWeight = Math.Round((IsDiscount ? NetWeight - (NetWeight * (WeightDiscountValue / 100m)) : NetWeight - DeductWeightValue), WeightValueDisplayFormat, MidpointRounding.AwayFromZero);
        }

        public event EventHandler WeightValueRequest;
        private Timer _timer;
        private int _emptyWeightCheckCount;
        private AppSettingsSection _mainSettings;
        public AppSettingsSection MainSettings
        {
            get => _mainSettings;
            set
            {
                _mainSettings = value;
                if (value == null)
                {
                    return;
                }
                var val = value.Settings["Discount"].Value.TryGetInt();
                if (val == 0)
                {
                    return;
                }
                if (val == 1)
                {
                    DeductWeight = value.Settings["DiscountWeight"].Value ?? string.Empty;
                }
                else
                {
                    WeightDiscount = value.Settings["DiscountRate"].Value ?? string.Empty;
                }
                IsDiscount = val != 1;
            }
        }

        public WeightInputFormModel()
        {
            DiscountOptions = new Dictionary<string, bool>
            {
                {I18NService.Translate(LangKeys.重量), false },
                {I18NService.Translate(LangKeys.比率), true },
            };
            WeighingTypeOptions = new List<string> { 
                I18NService.Translate(LangKeys.销售), 
                I18NService.Translate(LangKeys.采购), 
                I18NService.Translate(LangKeys.其他), 
                I18NService.Translate(LangKeys.中转), 
                I18NService.Translate(LangKeys.入库), 
                I18NService.Translate(LangKeys.出库) 
            };
            WeighingType = WeighingTypeOptions.FirstOrDefault();

            _timer = new Timer
            {
                Interval = 100,
            };
            _timer.Elapsed += (_, __) =>
            {
                if (_emptyWeightCheckCount > 3)
                {
                    WeightValueRequest?.Invoke(this, new EventArgs());
                    _emptyWeightCheckCount = 0;
                    return;
                }
                if (GrossWeight == 0 || TareWeightValue == 0)
                {
                    _emptyWeightCheckCount++;
                }
            };
            Task.Run(async () =>
            {
                await Task.Delay(6000);
                _timer.Start();
            });


        }


        public void Dispose()
        {
            _timer?.Stop();
        }
    }
}
